package org.petstore.persistence.impl;

import org.petstore.domain.LineItem;
import org.petstore.persistence.LineItemDAO;
import org.petstore.persistence.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class LineItemDAOImpl implements LineItemDAO {
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    private static final String GET_LINE_ITEM_BY_ORDER_ID = "SELECT " +
            " ORDERID," +
            " LINENUM AS lineNumber," +
            " ITEMID," +
            " QUANTITY," +
            " UNITPRICE" +
            " FROM LINEITEM" +
            " WHERE ORDERID = ?";
    private static final String INSERT_LINE_ITEM = "INSERT INTO LINEITEM (ORDERID, LINENUM, ITEMID, QUANTITY, UNITPRICE)" +
            " VALUES (?, ?, ?, ?, ?)";

    /**
     * description 通过orderId获取List<LineItem>
     *
     * @param orderId:
     * @return List<LineItem>
     * @author huangzhangyan
     * @date 2021/10/31 23:28
     */
    @Override
    public List<LineItem> getLineItemsByOrderId(int orderId) {
        List<LineItem> lineItemList;
        try {
            lineItemList = template.query(GET_LINE_ITEM_BY_ORDER_ID, new BeanPropertyRowMapper<>(LineItem.class), orderId);
            return lineItemList;
        } catch (DataAccessException e) {
            return null;
        }
    }

    /**
     * description 插入LineItem
     *
     * @param lineItem:
     * @author huangzhangyan
     * @date 2021/10/31 23:44
     */
    @Override
    public void insertLineItem(LineItem lineItem) {
        template.update(INSERT_LINE_ITEM,
                lineItem.getOrderId(),
                lineItem.getLineNumber(),
                lineItem.getItemId(),
                lineItem.getQuantity(),
                lineItem.getUnitPrice());
    }
}
